/**
common.js
 * Created by yqq on 2019/4/24.
 */

// const pageConfig = require('./../store/config');

//深拷贝
function deepCopy(obj){
  var str, newobj = obj.constructor === Array ? [] : {};
  if(typeof obj !== 'object'){
    return;
  } else if(window.JSON){
    str = JSON.stringify(obj), //系列化对象
      newobj = JSON.parse(str); //还原
  } else {
    for(var i in obj){
      newobj[i] = typeof obj[i] === 'object' ?
        cloneObj(obj[i]) : obj[i];
    }
  }
  return newobj;
}
function setlocalStorage (key,val) {
  // localStorage.setItem(pageConfig.prefix+key,val)
  localStorage.setItem(key,val)
}
function getlocalStorage (key) {
  // let item = localStorage.getItem(pageConfig.prefix+key);
  let item = localStorage.getItem(key);
  return item
}
function removelocalStorage (key) {
  // localStorage.removeItem(pageConfig.prefix+key)
  localStorage.removeItem(key)
}
function checklocalStorage (key) {
  let userdata = getlocalStorage(key);
  if(!!userdata){
    try {
      userdata = JSON.parse(userdata)
      return userdata
    } catch (err){
      return false
    }
  }else{
    return false
  }

}


function dataURLtoFile(dataurl, filename) {//将base64转换为文件
  var arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1],
    bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
  while(n--){
    u8arr[n] = bstr.charCodeAt(n);
  }
  return new File([u8arr], filename, {type:mime});
}
function filetoDataURL(file,fun) {//将base64转换为文件
  console.log(file);
  var imgobj = file;
  //创建文件读取相关的变量
  var imgFileBase64='';
  if(!!window.FileReader){
    //创建读取文件的对象
    var reader = new FileReader();
    //为文件读取成功设置事件
    reader.onload = function(e) {
      //console.log("文件读取完成");
      imgFileBase64 = e.target.result;
      if(!!fun && !!imgFileBase64){
        fun(imgFileBase64)
      }
    };
    //正式读取文件
    reader.readAsDataURL(imgobj);
  }else{
    if (!imgobj) {
      return;
    }
    // if(imgobj.size>300*1024){
    //   this.$alertShow('上传图片必须300K以内')
    //   return
    // }
    var imgsize = (imgobj.size / 1024).toFixed(0);
    var imageUrl = getObjectURL(imgobj);
    convertImgToBase64(
      imageUrl,
      function(imgele) {
        console.log(' console.log(imgele)')
        imgFileBase64 = imgele;
        if(!!fun && !!imgFileBase64){
          fun(imgFileBase64)
        }
      },
      imgsize
    );
  }

}

function getObjectURL(file) {
  var url = null;
  if (window.createObjectURL != undefined) {
    // basic
    url = window.createObjectURL(file);
  } else if (window.URL != undefined) {
    // mozilla(firefox)
    url = window.URL.createObjectURL(file);
  } else if (window.webkitURL != undefined) {
    // web_kit or chrome
    url = window.webkitURL.createObjectURL(file);
  }
  return url;
}
function convertImgToBase64(url, callback, size) {
  var canvas = document.createElement("CANVAS");
  var ctx = canvas.getContext("2d");
  var img = new Image();
  size = parseInt(size);
  img.crossOrigin = "Anonymous";
  img.onload = function() {
    var width = img.width;
    var height = img.height;
    var rate = 1;
    if (width > 800 && size > 800) {
      rate = 800 / size;
    }
    canvas.width = width * rate;
    canvas.height = height * rate;
    ctx.drawImage(
      img,
      0,
      0,
      width,
      height,
      0,
      0,
      width * rate,
      height * rate
    );
    var dataURL = canvas.toDataURL("image/jpeg", 1);
    callback.call(this, dataURL);
    canvas = null;
  };
  img.src = url;

}
function isJSON(str) {
  if (typeof str == 'string') {
    try {
      var obj = JSON.parse(str);
      if (typeof obj == 'object' && obj) {
        return true;
      } else {
        return false;
      }

    } catch (e) {
      console.log('error：' + str + '!!!' + e);
      return false
    }
  } else {

    return false
  }

}
/*获取当前的日期时间 格式“yyyy-MM-dd HH:MM:SS”*/
function getNowFormatDate() {
  var date = new Date();
  var seperator1 = "-";
  var seperator2 = ":";
  var month = date.getMonth() + 1;
  var strDate = date.getDate();
  var Hours =  date.getHours();
  var Minutes =  date.getMinutes();
  var Seconds =  date.getSeconds();

  if (month >= 1 && month <= 9) {
    month = "0" + month;
  }
  if (strDate >= 0 && strDate <= 9) {
    strDate = "0" + strDate;
  }
  if (Hours >= 0 && Hours <= 9) {
    Hours = "0" + Hours;
  }
  if (Minutes >= 0 && Minutes <= 9) {
    Minutes = "0" + Minutes;
  }
  if (Seconds >= 0 && Seconds <= 9) {
    Seconds = "0" + Seconds;
  }

  var currentdate = date.getFullYear() + seperator1 + month + seperator1 + strDate
    + " " + Hours + seperator2 + Minutes + seperator2 + Seconds;
  return currentdate;
}
/* 获取前后几个月日期
* @date 格式为yyyy-mm-dd的日期，如：2014-01-25
* @num number
*/
function getPreMonth(date,num) {
  var arr = date.split('-');
  var year = arr[0]; //获取当前日期的年份
  var month = arr[1]; //获取当前日期的月份
  var day = arr[2]; //获取当前日期的日
  var days = new Date(year, month, 0);
  days = days.getDate(); //获取当前日期中月的天数
  var year2 = year;
  var month2 = parseInt(month) + num;
  if (month2 == 0) {
    year2 = parseInt(year2) - 1;
    month2 = 12;
  }
  var day2 = day;
  var days2 = new Date(year2, month2, 0);
  days2 = days2.getDate();
  if (day2 > days2) {
    day2 = days2;
  }
  if (month2 < 10) {
    month2 = '0' + month2;
  }
  var t2 = year2 + '-' + month2 + '-' + day2;
  return t2;
}

let common ={
  deepCopy:deepCopy,
  setlocalStorage:setlocalStorage,
  getlocalStorage:getlocalStorage,
  removelocalStorage:removelocalStorage,
  checklocalStorage:checklocalStorage,
  dataURLtoFile:dataURLtoFile,
  filetoDataURL:filetoDataURL,
  getNowFormatDate:getNowFormatDate,
  getPreMonth:getPreMonth,
  isJSON:isJSON,
}

export const $common = common